FloatParser.packFloatBits_   B
last analyzed

Complexity

Conditions 6

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 19
dl 0
loc 31
rs 8.5166
c 0
b 0
f 0
1
/*
2
 * Copyright (c) 2018-2019 Rafael da Silva Rocha.
3
 * Copyright (c) 2013 DeNA Co., Ltd.
4
 * Copyright (c) 2010, Linden Research, Inc
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining
7
 * a copy of this software and associated documentation files (the
8
 * "Software"), to deal in the Software without restriction, including
9
 * without limitation the rights to use, copy, modify, merge, publish,
10
 * distribute, sublicense, and/or sell copies of the Software, and to
11
 * permit persons to whom the Software is furnished to do so, subject to
12
 * the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be
15
 * included in all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
 *
25
 */
26
27
/**
28
 * @fileoverview Encode and decode IEEE 754 floating point numbers.
29
 * @see https://github.com/rochars/byte-data
30
 * @see https://bitbucket.org/lindenlab/llsd/raw/7d2646cd3f9b4c806e73aebc4b32bd81e4047fdc/js/typedarray.js
31
 * @see https://github.com/kazuho/ieee754.js/blob/master/ieee754.js
32
 */
33
34
/**
35
 * A class to encode and decode IEEE 754 floating-point numbers.
36
 */
37
export class FloatParser {
38
39
  /**
40
   * Pack a IEEE 754 floating point number.
41
   * @param {number} ebits The exponent bits.
42
   * @param {number} fbits The fraction bits.
43
   */
44
  constructor(ebits, fbits) {
45
    /**
46
     * @type {number}
47
     */
48
    this.offset = Math.ceil((ebits + fbits) / 8);
49
    /**
50
     * @type {number}
51
     * @private
52
     */
53
    this.ebits = ebits;
54
    /**
55
     * @type {number}
56
     * @private
57
     */
58
    this.fbits = fbits;
59
    /**
60
     * @type {number}
61
     * @private
62
     */
63
    this.bias = (1 << (ebits - 1)) - 1;
64
    /**
65
     * @type {number}
66
     * @private
67
     */
68
    this.biasP2 = Math.pow(2, this.bias + 1);
69
    /**
70
     * @type {number}
71
     * @private
72
     */
73
    this.ebitsFbits = (ebits + fbits);
74
    /**
75
     * @type {number}
76
     * @private
77
     */
78
    this.fbias = Math.pow(2, -(8 * this.offset - 1 - ebits));
79
  }
80
81
  /**
82
   * Pack a IEEE 754 floating point number.
83
   * @param {!Uint8Array|!Array<number>} buffer The buffer.
84
   * @param {number} num The number.
85
   * @param {number} index The index to write on the buffer.
86
   * @return {number} The next index to write on the buffer.
87
   * @throws {TypeError} If input is not a number.
88
   */
89
  pack(buffer, num, index) {
90
    // Only numbers can be packed
91
    if (typeof num !== 'number') {
92
      throw new TypeError();
93
    }
94
    // Round overflows
95
    if (Math.abs(num) > this.biasP2 - (this.ebitsFbits * 2)) {
96
      num = num < 0 ? -Infinity : Infinity;
97
    }
98
    /**
99
     * sign, need this to handle negative zero
100
     * @see http://cwestblog.com/2014/02/25/javascript-testing-for-negative-zero/
101
     * @type {number}
102
     */
103
    let sign = (((num = +num) || 1 / num) < 0) ? 1 : num < 0 ? 1 : 0;
104
    num = Math.abs(num);
105
    /** @type {number} */
106
    let exp = Math.min(Math.floor(Math.log(num) / Math.LN2), 1023);
107
    /** @type {number} */
108
    let fraction = roundToEven(num / Math.pow(2, exp) * Math.pow(2, this.fbits));
109
    // NaN
110
    if (num !== num) {
111
      fraction = Math.pow(2, this.fbits - 1);
112
      exp = (1 << this.ebits) - 1;
113
    // Number
114
    } else if (num !== 0) {
115
      if (num >= Math.pow(2, 1 - this.bias)) {
116
        if (fraction / Math.pow(2, this.fbits) >= 2) {
117
          exp = exp + 1;
118
          fraction = 1;
119
        }
120
        // Overflow
121
        if (exp > this.bias) {
122
          exp = (1 << this.ebits) - 1;
123
          fraction = 0;
124
        } else {
125
          exp = exp + this.bias;
126
          fraction = roundToEven(fraction) - Math.pow(2, this.fbits);
127
        }
128
      } else {
129
        fraction = roundToEven(num / Math.pow(2, 1 - this.bias - this.fbits));
130
        exp = 0;
131
      } 
132
    }
133
    return this.packFloatBits_(buffer, index, sign, exp, fraction);
134
  }
135
136
  /**
137
   * Unpack a IEEE 754 floating point number.
138
   * Derived from IEEE754 by DeNA Co., Ltd., MIT License. 
139
   * Adapted to handle NaN. Should port the solution to the original repo.
140
   * @param {!Uint8Array|!Array<number>} buffer The buffer.
141
   * @param {number} index The index to read from the buffer.
142
   * @return {number} The floating point number.
143
   */
144
  unpack(buffer, index) {
145
    /** @type {number} */
146
    let eMax = (1 << this.ebits) - 1;
147
    /** @type {number} */
148
    let significand;
149
    /** @type {string} */
150
    let leftBits = "";
151
    for (let i = this.offset - 1; i >= 0 ; i--) {
152
      /** @type {string} */
153
      let t = buffer[i + index].toString(2);
154
      leftBits += "00000000".substring(t.length) + t;
155
    }
156
    /** @type {number} */
157
    let sign = leftBits.charAt(0) == "1" ? -1 : 1;
158
    leftBits = leftBits.substring(1);
159
    /** @type {number} */
160
    let exponent = parseInt(leftBits.substring(0, this.ebits), 2);
161
    leftBits = leftBits.substring(this.ebits);
162
    if (exponent == eMax) {
163
      if (parseInt(leftBits, 2) !== 0) {
164
        return NaN;
165
      }
166
      return sign * Infinity;  
167
    } else if (exponent === 0) {
168
      exponent += 1;
169
      significand = parseInt(leftBits, 2);
170
    } else {
171
      significand = parseInt("1" + leftBits, 2);
172
    }
173
    return sign * significand * this.fbias * Math.pow(2, exponent - this.bias);
174
  }
175
176
  /**
177
   * Pack a IEEE754 from its sign, exponent and fraction bits
178
   * and place it in a byte buffer.
179
   * @param {!Uint8Array|!Array<number>} buffer The byte buffer to write to.
180
   * @param {number} index The buffer index to write.
181
   * @param {number} sign The sign.
182
   * @param {number} exp the exponent.
183
   * @param {number} fraction The fraction.
184
   * @return {number}
185
   * @private
186
   */
187
  packFloatBits_(buffer, index, sign, exp, fraction) {
188
    /** @type {!Array<number>} */
189
    let bits = [];
190
    // the sign
191
    bits.push(sign);
192
    // the exponent
193
    for (let i = this.ebits; i > 0; i -= 1) {
194
      bits[i] = (exp % 2 ? 1 : 0);
195
      exp = Math.floor(exp / 2);
196
    }
197
    // the fraction
198
    let len = bits.length;
199
    for (let i = this.fbits; i > 0; i -= 1) {
200
      bits[len + i] = (fraction % 2 ? 1 : 0);
201
      fraction = Math.floor(fraction / 2);
202
    }
203
    // pack as bytes
204
    /** @type {string} */
205
    let str = bits.join('');
206
    /** @type {number} */
207
    let offset = this.offset + index - 1;
208
    /** @type {number} */
209
    let k = index;
210
    while (offset >= index) {
211
      buffer[offset] = parseInt(str.substring(0, 8), 2);
212
      str = str.substring(8);
213
      offset--;
214
      k++;
215
    }
216
    return k;
217
  }
218
}
219
220
/**
221
 * Round a number to its nearest even value.
222
 * @param {number} n The number.
223
 * @return {number}
224
 * @private
225
 */
226
function roundToEven(n) {
227
  /** @type {number} */
228
  let w = Math.floor(n);
229
  let f = n - w;
230
  if (f < 0.5) {
231
    return w;
232
  }
233
  if (f > 0.5) {
234
    return w + 1;
235
  }
236
  return w % 2 ? w + 1 : w;
237
}
238